package com.itheima.case2.service.impl;

import com.itheima.case2.dao.UserMapper;
import com.itheima.case2.dao.UserRoleMapper;
import com.itheima.case2.pojo.User;
import com.itheima.case2.service.UserService;
import com.itheima.case2.utils.SqlSessionUtil;
import com.itheima.case2.vo.PageBean;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class UserServiceImpl implements UserService {
    public User login(String username, String password) {
        SqlSession sqlSession = SqlSessionUtil.getSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user = mapper.login(username,password);
        sqlSession.close();
        return user;
    }

    public PageBean findAllUserByPage (int curPage, int pageSize){
        PageBean<User> pb = new PageBean<>();
        pb.setCurPage(curPage);
        pb.setPageSize(pageSize);
        UserMapper mapper = SqlSessionUtil.getProxyMapper(UserMapper.class);
        List<User> userList = mapper.findAllUsersByPage(pb.getStartIndex(), pageSize);
       pb.setList(userList);
        int count= mapper.queryUsersCount();
        pb.setCount(count);
      return pb;
    }


    @Override
    public void updataUser(User user) {
        UserMapper userMapper = SqlSessionUtil.getProxyMapper(UserMapper.class);
        userMapper.updataUser(user);
        UserRoleMapper userRoleMapper = SqlSessionUtil.getProxyMapper(UserRoleMapper.class);
        userRoleMapper.deleteDataByUID(Integer.parseInt(user.getId()));
        List<String> roleIds = user.getRoleIds();
        for (String roleId : roleIds) {
            userRoleMapper.addUserIdandRoleId(Integer.parseInt(user.getId()),Integer.parseInt(roleId));

        }
    }
}
